import { defineStore } from 'pinia'
import { ref } from 'vue'
//引入接口
import { reqLogin, reqLoginByEmail } from '@/api/auth'
import type { UserLoginByEmailParams, UserLoginParams } from '@/api/auth/type'
import { reqMyUserInfo } from '@/api/user'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { ElLoading, ElMessage } from 'element-plus'
import pinia from '..'
import { UserInfoRes } from '@/api/user/type'
import router from '@/router'
import { useRouterStore } from './router'

//创建用户小仓库
const useUserStore = defineStore('User', () => {
  const token = ref<string>(GET_TOKEN() as string)
  const sideMode = ref<string>('#fff')
  const activeColor = ref<string>('#1890ff')
  const userInfo = ref<UserInfoRes>({
    id: 0,
    name: '',
    username: '',
    email: '',
    avatar: '',
    sign: '',
    sex: 0,
    roleIds: [],
    roles: [],
    status: 1,
    deleted: 0,
    createTime: '',
    updateTime: '',
  })
  const usereAsyncRoute = ref([])
  async function userLogin(params: UserLoginParams) {
    try {
      const { data } = await reqLogin(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      await getUserInfo()
      const routerStore = useRouterStore()
      await routerStore.SetAsyncRouter(userInfo.value.roleIds[0])
      const asyncRouters = routerStore.asyncRouters
      asyncRouters.forEach((asyncRouter) => {
        router.addRoute(asyncRouter)
      })
      await router.replace({ name: 'home' })
    } catch (error) {
      //登录失败的提示信息
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function userLoginByEmail(params: UserLoginByEmailParams) {
    try {
      const { data } = await reqLoginByEmail(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      await getUserInfo()
      const routerStore = useRouterStore()
      await routerStore.SetAsyncRouter(userInfo.value.roleIds[0])
      const asyncRouters = routerStore.asyncRouters
      asyncRouters.forEach((asyncRouter) => {
        router.addRoute(asyncRouter)
      })
      await router.replace({ name: 'home' })
    } catch (error) {
      //登录失败的提示信息
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function getUserInfo() {
    try {
      const { data } = await reqMyUserInfo()
      userInfo.value = data
    } catch (error) {
      if (error instanceof Error) {
        ElMessage.error(error.message)
        Promise.reject(new Error(error.message))
      }
    }
  }
  async function userLogout() {
    REMOVE_TOKEN()
    token.value = ''
  }

  return {
    token,
    userInfo,
    usereAsyncRoute,
    sideMode,
    activeColor,
    userLogout,
    userLogin,
    userLoginByEmail,
    getUserInfo,
  }
})
//对外暴露获取小仓库方法
export default useUserStore

// 非setup
export function useUserStoreHook() {
  return useUserStore(pinia)
}
